import { Modal } from "antd";
import QRCode from "qrcode.react";

import React, { useEffect, useState } from "react";
import ProForm, { ProFormSelect, ProFormText } from "@ant-design/pro-form";
import { pageIdField, pageUrl } from "@/components/QrcodeDown/const";
import ProDescriptions from "@ant-design/pro-descriptions";

declare type QRCodeDownData = {
  value: string;
  codeName?: string; // 下载的二维码文件名称
  linkText?: string;  // 显示文本
  size?: number; // 二维码大小 单位 像素
  width?: number;  //  展示二维码大小 单位 px
  height?: number;
  imageSettings?: ImageSettings
}

declare type ImageSettings = {
  src: string;  // 图片地址
  height: number; // 高度 单位 像素
  width: number; // 长度 单位 像素
  excavate: boolean;
  x?: number;
  y?: number;
};

const getBase64Image = (src: string) => {
  return new Promise(resolve => {
    const img = new Image()
    img.setAttribute('crossOrigin', 'anonymous');
    img.src = src
    img.onload = function () {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      ctx?.drawImage(img, 0, 0, img.width, img.height)
      const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
      const dataURL = canvas.toDataURL('image/' + ext)
      resolve(dataURL)
    }
  })
}
/**
 * 二维码预览
 * @param param0
 * @returns
 */
const QRCodeDown: React.FC<QRCodeDownData> = ({ value, codeName, linkText = '', size = 1024, width = 250, height = 250, imageSettings }) => {
  const [urlParams, setUrlParams] = useState(value.split('?'))
  const [qrValue, setQrValue] = useState(value)
  const [searchVal, setSearchVal] = useState('');
  //下载二维码
  const downQR = () => {
    let canvas = document.getElementById('qrCode');
    let name = linkText + '的二维码';
    // @ts-ignore
    let href = canvas?.toDataURL(); // 获取canvas对应的base64编码
    let a = document.createElement('a'); // 创建a标签
    a.download = codeName ? codeName + name : '二维码'; // 设置图片名字
    a.href = href;
    a.dispatchEvent(new MouseEvent('click'));
  };
  const [createQrVisible, handleQrVisible] = useState<boolean>(false);
  useEffect(() => {
    setQrValue(() => `${urlParams[0]}?${urlParams[1]}${searchVal ? '&' + searchVal : ''}`)
  }, [searchVal, urlParams]);
  return <>
    <a onClick={async () => {
      if (imageSettings && imageSettings?.src) {
        let base = await getBase64Image(imageSettings?.src)
        if (base) {
          // @ts-ignore
          imageSettings.src = base;
        }

      }

      handleQrVisible(true)
    }}> {linkText || '查看二维码'}</a>
    <Modal open={createQrVisible} footer={null} width={width + width / 4} onCancel={() => handleQrVisible(false)}>
      <ProForm
        submitter={{
          // 配置按钮的属性
          resetButtonProps: {
            style: {
              // 隐藏重置按钮
              display: 'none',
            },
          },
          submitButtonProps: {
            style: {
              // 隐藏确认按钮
              display: 'none',
            },
          },
        }}>
        <ProFormSelect
          name="url"
          label="页面路径"
          valueEnum={pageUrl}
          placeholder="请选择需要跳转的页面"
          width="xl"
          fieldProps={{
            defaultValue: urlParams[0],
            onChange: (v) => {
              setUrlParams(prev => [v, prev[1]])
              setSearchVal(pageIdField[v] ? pageIdField[v] + '=' : '')
            }
          }}
        />
        <ProFormText
          name="search"
          label="链接参数"
          placeholder="xxxkey=xxxvalue&xxxkey=xxxval"
          fieldProps={{
            value: searchVal,
            onChange: (e) => {
              setSearchVal(e.target.value)
            }
          }}
        />
        <ProDescriptions
          column={1}
        >
          <ProDescriptions.Item label="标识码">{linkText || <h2>{linkText}</h2>}</ProDescriptions.Item>
          <ProDescriptions.Item label="二维码">
            <div className="codeInfo">
              <QRCode imageSettings={imageSettings} value={qrValue} size={size} style={{ width: imageSettings?.width ? imageSettings?.width : width, height: imageSettings?.height ? imageSettings?.height : height }} id="qrCode" />
              <div>
                <a onClick={downQR}>下载二维码</a>
              </div>
            </div>
          </ProDescriptions.Item>
        </ProDescriptions>
      </ProForm>
    </Modal >
  </>
}

export default QRCodeDown
